package main

import (
	"encoding/json"
	"fmt"
	"net"
	"strings"
)

var MonitorData = make(chan []byte, 10000)

func pprint() {
	for {
		select {
		case msg, ok := <-MonitorData:
			if !ok {
				break
			}
			var pack map[string]interface{}
			if err := json.Unmarshal(msg, &pack); err != nil {
				continue
			}
			var (
				timeStamp uint64
				host      string
				service   string
			)
			status := pack["status"].(float64)
			if int(status) != 0 {
				log.Error(string(msg))
				continue
			}
			if tm, ok := pack["date"].(float64); ok {
				timeStamp = uint64(tm)
			}
			host = pack["host"].(string)
			service = pack["service"].(string)
			for k, v := range pack["data"].(map[string]interface{}) {
				log.Info("put %s.%s %v %v host=%s", service, k, timeStamp, v, host)
			}
		}
	}
}

func ParseToTsdb(data []byte) {
	var pack map[string]interface{}
	if err := json.Unmarshal(data, &pack); err != nil {
		return
	}
	var (
		timeStamp uint64
		host      string
		service   string
	)
	status := pack["status"].(float64)
	if int(status) != 0 {
		log.Error(string(data))
		return
	}
	if tm, ok := pack["date"].(float64); ok {
		timeStamp = uint64(tm)
	}
	host = pack["host"].(string)
	service = pack["service"].(string)
	for k, v := range pack["data"].(map[string]interface{}) {
		MonitorData <- []byte(fmt.Sprintf("put %s.%s %v %v host=%s\n", service, k, timeStamp, v, host))
	}
}

func send() {
	addr, _ := net.ResolveTCPAddr("tcp4", "10.10.0.157:4242")
	conn, err := net.DialTCP("tcp4", nil, addr)
	if err != nil {
		log.Error("connect error <%v>", err)
	}
	for {
		select {
		case msg, ok := <-MonitorData:
			if !ok {
				break
			}
			_, err := conn.Write(msg)
			if err != nil {
				fmt.Println(err)
				continue
			}
			log.Info("Write to opentsdb:%s",strings.Trim(string(msg),"\n"))
		}
	}
}
